package com.example.xsssglxt.controller;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.listener.ReadListener;
import com.example.xsssglxt.entity.Student;
import com.example.xsssglxt.mapper.StudentMapper;

import java.util.ArrayList;
import java.util.List;


public class DataListener extends AnalysisEventListener<Student> {
    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    private StudentMapper studentMapper;
    public DataListener(StudentMapper studentMapper){
        this.studentMapper = studentMapper;
    }
    List<Student> list = new ArrayList<Student>();
    //读取数据会执行这方法
    @Override
    public void invoke(Student student, AnalysisContext analysisContext) {

        list.add(student);

        if (list.size() >= BATCH_COUNT){
            list.clear();
        }
    }
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        System.out.println("所有数据解析完成");
    }
    private void saveData(){
        System.out.println(this.studentMapper);
        System.out.println("{" + list.size() + "}条数据，开始存储数据库" );
        for (Student student : list) {
            studentMapper.insert(student);
        }
        System.out.println("存储数据库成功");
    }


}